#include "socket_utils.h"

int init_connection(int port, int maxClients)
{
   SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
   SOCKADDR_IN sin = { 0 };

   if(sock == INVALID_SOCKET)
   {
      perror("socket()");
      exit(errno);
   }

   sin.sin_addr.s_addr = htonl(INADDR_ANY);
   sin.sin_port = htons(port);
   sin.sin_family = AF_INET;

   if(bind(sock,(SOCKADDR *) &sin, sizeof sin) == SOCKET_ERROR)
   {
      perror("[init_connection] bind()");
      printf("\nsur le port %i\n", port);
      exit(errno);
   }

   if(listen(sock, maxClients) == SOCKET_ERROR)
   {
      perror("listen()");
      exit(errno);
   }
   return sock;
}

void remove_client(SOCKET *clients, int to_remove, int *actual)
{
   /* we remove the client in the array */
   memmove(clients + to_remove, clients + to_remove + 1, (*actual - to_remove - 1) * sizeof(SOCKET));
   /* number client - 1 */
   (*actual)--;
}

void write_client(SOCKET sock, const char *buffer)
{
   if(send(sock, buffer, strlen(buffer), 0) < 0)
   {
      perror("send()");
      exit(errno);
   }
}

int read_client(SOCKET sock, char *buffer, int tailleBuffer)
{
   int n = 0;
   if((n = recv(sock, buffer, tailleBuffer - 1, 0)) < 0)
   {
      perror("[read_client] Erreur de recv()");
      /* if recv error we disconnect the client */
      n = 0;
   }
   else
   {
	   buffer[n] = '\0'; //TODO : j'ai changé le n-1 en n, vérifier que ca fait rien foirer
   }
   //printf("[read_client] valeur de n : %i; contenu du buffer : %s\n", n, buffer);
   return n;
}

void end_connection(int sock)
{
   close(sock);
}
